package com.sch.wanandroid.network

import android.util.Log
import com.franmontiel.persistentcookiejar.ClearableCookieJar
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.google.gson.GsonBuilder
import com.sch.wanandroid.WanAndroidApplication
import com.sch.wanandroid.util.TextUtils
import com.tencent.mmkv.MMKV
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 * Created by Sch.
 * Date: 2020/12/11
 * description:
 */
object NetWorkManager {
    //实现cookies 持久化的一种简便方式
    var cookieJar: ClearableCookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(WanAndroidApplication.getContext()))
    private val okHttpClient by lazy {
        val httpLoggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
            Log.i("okHttpLog", TextUtils.unicodeToUTF_8(it))
        })
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        val interceptor = Interceptor { chain ->
            val original = chain.request()
            val requestBuilder = original.newBuilder()
                    .method(original.method(), original.body())
            val request = requestBuilder.build()
            chain.proceed(request)
        }
        //实现cookies 持久化的一种方式
        val readCookiesInterceptor = Interceptor { chain ->
            val builder = chain.request().newBuilder()
            val kv: MMKV = MMKV.defaultMMKV()
            val cookies: HashSet<String> =
                    kv.decodeStringSet("cookies", HashSet<String>()) as HashSet<String>
            for (cookie in cookies) {
                builder.addHeader("Cookie", cookie)
                Log.e("cookie", "read" + cookie)
            }
            chain.proceed(builder.build())
        }
        val saveCookiesInterceptor = Interceptor { chain ->
            val originalResponse = chain.proceed(chain.request())
            if (originalResponse.headers("Set-Cookie").isNotEmpty()) {
                val cookies: HashSet<String> = HashSet()
                for (header in originalResponse.headers("Set-Cookie")) {
                    cookies.add(header)
                    Log.e("cookie", "save" + header)
                }
                val kv: MMKV = MMKV.defaultMMKV()
                kv.encode("cookies", cookies)
            }
            originalResponse
        }

        OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(interceptor)
                .cookieJar(cookieJar)
                .connectTimeout(120L, TimeUnit.SECONDS)
                .readTimeout(120L, TimeUnit.SECONDS)
                .writeTimeout(120L, TimeUnit.SECONDS)
                .build()
    }

    private val retrofit by lazy {
        Retrofit.Builder()
                .baseUrl("https://www.wanandroid.com/")
                .client(okHttpClient)
                .addConverterFactory(
                        GsonConverterFactory.create(
                                GsonBuilder().enableComplexMapKeySerialization().create()
                        )
                )
                .build()
    }
    val apiService: ApiService by lazy { retrofit.create(ApiService::class.java) }

}